package artid.com.arttogoa.fragment;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import artid.com.arttogoa.R;
import artid.com.arttogoa.adapter.GridAdapter;
import artid.com.arttogoa.db.SDCache;
import artid.com.arttogoa.keeponrecord.GroupPhotoActivity;
import artid.com.arttogoa.parser.FilesBean;
import artid.com.arttogoa.task.CallbackSky;
import artid.com.arttogoa.util.AlertUtils;

public class LocalFragment extends Fragment {
	private GridView gv;
	private Handler mHandler;
	private List<FilesBean> filesList = new ArrayList<FilesBean>();
	private Activity mContext;
	View v;
	int index;
	private FilesBean fb;
	private float w, h;

	public LocalFragment(float w, float h) {
		// TODO Auto-generated constructor stub
		this.w = w;
		this.h = h;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
	 * android.view.ViewGroup, android.os.Bundle)
	 */
	@SuppressLint({ "HandlerLeak", "InflateParams" })
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v = inflater.inflate(R.layout.activity_driver, null);
		mContext = getActivity();
		gv = (GridView) v.findViewById(R.id.grid);
		gv.setVisibility(View.VISIBLE);
		// gv.setOnItemClickListener(new OnItemClickListener() {
		// @Override
		// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
		// long arg3) {
		// // TODO Auto-generated method stub
		// index = arg2;
		// fb = filesList.get(index);
		// Intent intent = new Intent(mContext, GroupPhotoActivity.class);
		// Bundle bundle = new Bundle();
		// bundle.putSerializable("image", fb);
		// intent.putExtras(bundle);
		// mContext.setResult(4, intent);// 返回页面1
		// mContext.finish();
		// }
		// });
		getAll();
		mHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				super.handleMessage(msg);
				switch (msg.what) {
				case 1:
					gv.setAdapter(new GridAdapter(mContext, filesList,
							SDCache.LOCAL, gv, false, new CallbackSky() {

								@Override
								public void callBack(int arg2) {
									// TODO Auto-generated method stub
									index = arg2;
									fb = filesList.get(index);
									if (w > 0 && h > 0) {
										BitmapFactory.Options options = new BitmapFactory.Options();

										/**
										 * 最关键在此，把options.inJustDecodeBounds =
										 * true; 这里再decodeFile()，返回的bitmap为空
										 * ，但此时调用options.outHeight时，已经包含了图片的高了
										 */
										options.inJustDecodeBounds = true;
										Bitmap bitmap = BitmapFactory
												.decodeFile(fb.getThumbURL(),
														options); // 此时返回的bitmap为null
										/**
										 * options.outHeight为原始图片的高
										 */
										Log.e("Test", "Bitmap Height == "
												+ options.outHeight);
										if (options.outHeight < h
												|| options.outWidth < w) {
											AlertUtils
													.initSubmitSumAlertDialog(
															getActivity(),
															"该图片质量不够，请换一张图片作为完整图");
											return;
										}
									}
									Intent intent = new Intent(mContext,
											GroupPhotoActivity.class);
									Bundle bundle = new Bundle();
									bundle.putSerializable("image", fb);
									intent.putExtras(bundle);
									mContext.setResult(4, intent);// 返回页面1
									mContext.finish();
								}
							}));
				}
			}

		};
		return v;
	}

	private void getAll() {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {

			return;
		}
		//
		// 显示进度条
		new Thread(new Runnable() {

			@Override
			public void run() {
				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = mContext
						.getContentResolver();

				// 只查询jpeg和png的图片
				Cursor mCursor = mContentResolver.query(mImageUri, null,
						MediaStore.Images.Media.MIME_TYPE + "=? or "
								+ MediaStore.Images.Media.MIME_TYPE + "=?",
						new String[] { "image/jpeg", "image/png" },
						MediaStore.Images.Media.DATE_ADDED + " DESC");

				while (mCursor.moveToNext()) {
					// 获取图片的路径
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATA));
					String text = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.TITLE));
					String size = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.SIZE));
					FilesBean fb = new FilesBean();
					fb.setThumbURL(path);
					fb.setName(text);
					fb.setFileSize(size);
					filesList.add(fb);
				}
				System.out.println("filesList=" + filesList.toString());
				mCursor.close();

				// 通知Handler扫描图片完成
				mHandler.sendEmptyMessage(1);

			}
		}).start();

	}

	private class FileComparator implements Comparator<File> {

		@Override
		public int compare(File lhs, File rhs) {
			if (lhs.lastModified() < rhs.lastModified()) {
				return 1;// 最后修改的照片在前
			} else {
				return -1;
			}
		}
	}

	private FileFilter filefiter = new FileFilter() {

		@Override
		public boolean accept(File f) {
			String tmp = f.getName().toLowerCase();
			if (tmp.endsWith(".png") || tmp.endsWith(".jpg")
					|| tmp.endsWith(".jpeg")) {
				return true;
			}
			return false;
		}

	};
}
